package com.hujiheng.paike.controller;


import com.hujiheng.paike.common.lang.Result;
import com.hujiheng.paike.pojo.ClassInfo;
import com.hujiheng.paike.pojo.Student;
import com.hujiheng.paike.service.ClassInfoService;
import com.hujiheng.paike.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassInfoService classInfoService;

    @RequestMapping(value = "/{studentId}")
    public Result test(@PathVariable("studentId") int studentId) {
        Student byId = studentService.getById(studentId);
        System.out.println(byId);
        return Result.success(byId);
    }

    @RequestMapping("/list")
    public Result getStudentList() {
        List<Student> studentList = studentService.getStudentList();
        return Result.success(studentList);
    }

    @RequestMapping("/edit")
    public Result edit(@Validated @RequestBody Student student) {
        ClassInfo classInfoById = classInfoService.getClassInfoById(student.getClassId());
        if (classInfoById == null) {
            return Result.fail("班级不存在");
        }
        int updateStudent = studentService.updateStudent(student);
        if (updateStudent != 1) {
            return Result.fail("修改失败");
        }
        System.out.println(student);
        return Result.success("修改成功");
    }

    @RequestMapping("/add")
    public Result add(@Validated @RequestBody Student student) {
        ClassInfo classInfoById = classInfoService.getClassInfoById(student.getClassId());
        if (classInfoById == null) {
            return Result.fail("班级不存在");
        }
        int updateStudent = studentService.addStudent(student);
        if (updateStudent < 1) {
            return Result.fail("添加失败");
        }
        System.out.println(student);
        return Result.success("添加成功");
    }

    @RequestMapping("/del/{studentId}")
    public Result del(@PathVariable("studentId") int studentId) {
        int deleteStudent = studentService.deleteStudent(studentId);
        if (deleteStudent < 1) {
            return Result.fail("删除失败");
        }
        System.out.println("studentId = " + studentId);
        return Result.success("删除成功");
    }
}
